package org.jeecg.modules.my.cblSpuCatalog.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.my.cblSpuCatalog.entity.CblSpuCatalog;
import org.jeecg.modules.my.cblSpuCatalog.entity.Duolld;
import org.jeecg.modules.my.cblSpuCatalog.service.ICblSpuCatalogService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: spu分类
 * @Author: jeecg-boot
 * @Date:   2020-09-05
 * @Version: V1.0
 */
@Api(tags="spu分类")
@RestController
@RequestMapping("/cblSpuCatalog/cblSpuCatalog")
@Slf4j
public class CblSpuCatalogController extends JeecgController<CblSpuCatalog, ICblSpuCatalogService>{
	@Autowired
	private ICblSpuCatalogService cblSpuCatalogService;

	 @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	 public Result<List<Duolld>> loadTreeRoot() {
		 Result<List<Duolld>> result = new Result<List<Duolld>>();
		 try {
			 List<CblSpuCatalog> ls = this.cblSpuCatalogService.list(new QueryWrapper<CblSpuCatalog>().eq("pid", 0));
			 List<Duolld> ls2 = new ArrayList<>();

			 for (CblSpuCatalog cblSpuCatalog: ls
				  ) {
				 Duolld duolld = new Duolld();
				 duolld.setValue(cblSpuCatalog.getId());
				 duolld.setLabel(cblSpuCatalog.getName());

				 ls2.add(duolld);
			 }

			 loadAllCategoryChildren(ls2);

			 result.setResult(ls2);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 递归求子节点 同步加载用到
	  */
	 private void loadAllCategoryChildren(List<Duolld> ls) {
		 for (Duolld tsm : ls) {
			 List<CblSpuCatalog> temp = this.cblSpuCatalogService.list(new QueryWrapper<CblSpuCatalog>().eq("pid", tsm.getValue()));
			 List<Duolld> ls2 = new ArrayList<>();

			 for (CblSpuCatalog cblSpuCatalog: temp
			 ) {
				 Duolld duolld = new Duolld();
				 duolld.setValue(cblSpuCatalog.getId());
				 duolld.setLabel(cblSpuCatalog.getName());

				 ls2.add(duolld);
			 }

			 if(ls2!=null && ls2.size()>0) {
				 tsm.setChildren(ls2);
				 loadAllCategoryChildren(ls2);
			 }
		 }
	 }
	
	/**
	 * 分页列表查询
	 *
	 * @param cblSpuCatalog
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "spu分类-分页列表查询")
	@ApiOperation(value="spu分类-分页列表查询", notes="spu分类-分页列表查询")
	@GetMapping(value = "/rootList")
	public Result<?> queryPageList(CblSpuCatalog cblSpuCatalog,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String parentId = cblSpuCatalog.getPid();
		if (oConvertUtils.isEmpty(parentId)) {
			parentId = "0";
		}
		cblSpuCatalog.setPid(null);
		QueryWrapper<CblSpuCatalog> queryWrapper = QueryGenerator.initQueryWrapper(cblSpuCatalog, req.getParameterMap());
		// 使用 eq 防止模糊查询
		queryWrapper.eq("pid", parentId);
		Page<CblSpuCatalog> page = new Page<CblSpuCatalog>(pageNo, pageSize);
		IPage<CblSpuCatalog> pageList = cblSpuCatalogService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 /**
      * 获取子数据
      * @param CblSpuCatalog
      * @param req
      * @return
      */
	@AutoLog(value = "spu分类-获取子数据")
	@ApiOperation(value="spu分类-获取子数据", notes="spu分类-获取子数据")
	@GetMapping(value = "/childList")
	public Result<?> queryPageList(CblSpuCatalog cblSpuCatalog,HttpServletRequest req) {
		QueryWrapper<CblSpuCatalog> queryWrapper = QueryGenerator.initQueryWrapper(cblSpuCatalog, req.getParameterMap());
		List<CblSpuCatalog> list = cblSpuCatalogService.list(queryWrapper);
		IPage<CblSpuCatalog> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.ok(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	@AutoLog(value = "spu分类-批量获取子数据")
    @ApiOperation(value="spu分类-批量获取子数据", notes="spu分类-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<CblSpuCatalog> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<CblSpuCatalog> list = cblSpuCatalogService.list(queryWrapper);
            IPage<CblSpuCatalog> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.ok(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param cblSpuCatalog
	 * @return
	 */
	@AutoLog(value = "spu分类-添加")
	@ApiOperation(value="spu分类-添加", notes="spu分类-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CblSpuCatalog cblSpuCatalog) {
		cblSpuCatalogService.addCblSpuCatalog(cblSpuCatalog);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cblSpuCatalog
	 * @return
	 */
	@AutoLog(value = "spu分类-编辑")
	@ApiOperation(value="spu分类-编辑", notes="spu分类-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CblSpuCatalog cblSpuCatalog) {
		cblSpuCatalogService.updateCblSpuCatalog(cblSpuCatalog);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "spu分类-通过id删除")
	@ApiOperation(value="spu分类-通过id删除", notes="spu分类-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		cblSpuCatalogService.deleteCblSpuCatalog(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "spu分类-批量删除")
	@ApiOperation(value="spu分类-批量删除", notes="spu分类-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cblSpuCatalogService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "spu分类-通过id查询")
	@ApiOperation(value="spu分类-通过id查询", notes="spu分类-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CblSpuCatalog cblSpuCatalog = cblSpuCatalogService.getById(id);
		if(cblSpuCatalog==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(cblSpuCatalog);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cblSpuCatalog
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CblSpuCatalog cblSpuCatalog) {
		return super.exportXls(request, cblSpuCatalog, CblSpuCatalog.class, "spu分类");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, CblSpuCatalog.class);
    }

}
